package com.csdj.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zyq
 * @Date 2022/12/14 10:33
 * @ClassName: JwtAuthenticationTokenFilter
 * @Description: jwt 过滤器
 * @Version 1.0
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //请求拦截处理 用户请求是否携带token信息
        //通过 http请求 拿取 请求头信息
        String header = request.getHeader(this.tokenHeader);
        //判断 请求头不为空 并且 令牌模式是 Bear 开头
        if (header!=null&&header.startsWith(this.tokenHead)){
            //key:Authorization  value: Bear xxxxxxx
            //截取token
            String authToken = header.substring(tokenHead.length());
            //根据token 获取用户名
            String username = jwtTokenUtil.getUserNameFormToken(authToken);
            //用户名 存在 但是 授权管理中没有 授权信息
            if(username!=null&&
                    SecurityContextHolder.getContext()
                            .getAuthentication()==null){
                //重新加载 登录逻辑
                UserDetails userDetails = userDetailsService.loadUserByUsername(
                        username);
                //判断token是否失效 重新设置 用户对象
                if(jwtTokenUtil.validateToken(authToken,userDetails)){
                    //设置 用户对象
                    UsernamePasswordAuthenticationToken authenticationToken
                            = new UsernamePasswordAuthenticationToken(userDetails,
                            null,
                            userDetails.getAuthorities());
                    //设置 请求 重新 构建加载 资源信息
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource()
                            .buildDetails(request));

                    //重新设置到 security的全局实例中
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }

            }
        }

        filterChain.doFilter(request,response); //通过过滤
    }
}
